<template>
  <div>
    <el-form style="width: 60%" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
             class="demo-ruleForm">
      <el-form-item label="课程名称" prop="cname">
        <el-input v-model.trim="ruleForm.cname" :value="ruleForm.cname"></el-input>
      </el-form-item>
      <el-form-item label="学分" prop="ccredit">
        <el-input v-model.number="ruleForm.ccredit" :value="ruleForm.ccredit"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button @click="test">test</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'editorCourse',
  data () {
    return {
      ruleForm: {
        cid: null,
        cname: null,
        ccredit: null
      },
      rules: {
        cname: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          },
        ],
        ccredit: [
          {
            required: true,
            message: '请输入学分',
            trigger: 'change'
          },
          {
            type: 'number',
            message: '请输入数字',
            trigger: 'change'
          },
        ],
      }
    }
  },
  created () {
    this.ruleForm.cid = this.$route.query.cid || 7
    axios.get('http://localhost:9000/course/findById/' + this.ruleForm.cid).then(response => {
      this.ruleForm = response.data[0]
    })
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const _this = this
          axios.put('http://localhost:9000/course/updateCourse', this.ruleForm).then(function (resp) {
            if (resp.data) {
              _this.$message({
                showClose: true,
                message: '编辑成功',
                type: 'success'
              })
            } else {
              _this.$message({
                showClose: true,
                message: '修改失败',
                type: 'error'
              });
            }
            _this.$router.push('/courseList')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    test () {
      console.log(this.ruleForm)
    }
  },
}
</script>

<style scoped>

</style>
